package com.stylefeng.guns.core.aop;

import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.domain.vo.ResultBean;
import com.stylefeng.guns.core.exception.CheckException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

/**
 * 切面
 */
@Slf4j  //日志注解
@Aspect     //切面
@Order(5)       //执行顺序
@Component      //一般不知道是哪个分类是，就用这玩意将他注入到spring容器中
public class HandlerException {
    /**
     * 切点，找到那些方面要切
     */
    @Pointcut("execution(public * com.stylefeng.guns.modular.system.controller.*.*(..))")
    public void webException() {
    }

    /**
     * 环切，执行方法前后都切
     *
     * @param proceedingJoinPoint
     * @return
     */
    @Around("webException()")
    public Object handlerControllerMethod(ProceedingJoinPoint proceedingJoinPoint) {
        Object resultBean;
        try {
            long startTime = System.currentTimeMillis();
            resultBean = proceedingJoinPoint.proceed();

            long endTime = System.currentTimeMillis() - startTime;

            log.info("最后花费的时间为：" + endTime);
        } catch (Throwable e) {
            resultBean = handlerException(e);
        }
        return resultBean;
    }

    /**
     * 这个是判断异常的类型
     *
     * @param throwable
     * @return
     */
    private Object handlerException(Throwable throwable) {
        Result<?> resultBean = new Result();
        if (throwable instanceof CheckException || throwable instanceof IllegalArgumentException) {
            resultBean.setMessage(throwable.getLocalizedMessage());
            resultBean.setCode(ResultBean.CHECK_FAIL);
        } else if (throwable instanceof UnauthenticatedException) {
            resultBean.setMessage("权限异常，请联系管理员");
            resultBean.setCode(ResultBean.AUTH_EXCEPTION);
        } else if (throwable instanceof DuplicateKeyException) {
            resultBean.setMessage("添加数据失败，唯一索引约束下数据重复！");
            resultBean.setCode(ResultBean.UNQ_INDEX_EXCEPTION);
        } else if (throwable instanceof NullPointerException) {//空指针异常
            resultBean.setMessage("session失效，请重新登录!");
            resultBean.setCode(ResultBean.NULL_POINT_EXCEPTION);
        } else {
            log.error("未知异常：", throwable);
            resultBean.setMessage(throwable.getMessage());
            resultBean.setCode(ResultBean.UNKNOWN_EXCEPTION);
        }
        return resultBean;
    }

}
